//
//  AppDelegate.m
//  01_kakin
//
//  Created by 佐藤 歩 on 12/03/04.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize isPurchase = _isPurchase;

- (void)dealloc
{
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [ UIColor whiteColor ];
    
    /*== DBの初期化 ==*/
    [ self databaseCopy ];
    
    /*== ユーザーでフォルトの初期化 ==*/
    [ DefaultUril initUserDefaults ];
    
    /*=== オープニング ===*/
    
    UIView *openView = [[ UIView alloc ]initWithFrame:[[UIScreen mainScreen ]bounds ]];
    UIImageView *imgView = [[ UIImageView alloc ]initWithFrame:CGRectMake(10, 90, 300, 300) ];
    imgView.image = [ UIImage imageNamed:IMG_Logo ];
    [openView addSubview:imgView];
    
    [ self.window addSubview:openView ];
    
    // 画面を表示
    [self.window makeKeyAndVisible];
    
    // アニメーション
    [UIView animateWithDuration:3.0 animations:^{ imgView.alpha = 0.0; } 
                     completion:^(BOOL finished) { [ imgView removeFromSuperview ],[ self addRootView ];}
     ];
    
    
    [ imgView release ];
    [ openView release ];
    return YES;
}

// オープニングアニメーション後の処理
-(void)addRootView{
    
    /*== main画面のセット ==*/
    MainViewController *MainView = [[ MainViewController alloc ]initWithNibName:@"MainViewController" bundle:nil];
    SANavigationController *navicon = [[ SANavigationController alloc ]initWithRootViewController:MainView];
    navicon.navigationBarHidden = YES;
    
    [self.window setRootViewController:navicon];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [ MainView release];
    [ navicon release ];

}


- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}


/* ============================================================================== */
#pragma mark - dataBase
/* ============================================================================== */

-(void)databaseCopy
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
    
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths lastObject];
	NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DBname];
	BOOL isExist = [fileManager fileExistsAtPath:writableDBPath];
	if (isExist) return;//存在するならreturn
    
	// 存在しなければ、リソースフォルダからユーザーフォルダにデータベースをコピーする
	NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DBname];
	isExist = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
	if (!isExist) {
		//失敗したら警告を表示
		NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}
}

/* ============================================================================== */
#pragma mark - set alerm
/* ============================================================================== */

- (void)addAlerm :(int)hourNumber :(int)minuteNumber file:(NSString*)soundFile {
	[[UIApplication sharedApplication] cancelAllLocalNotifications];
	
//	int hourNumber = [[self.hoursArray objectAtIndex: [[self.settingDict objectForKey: @"alerm_hour_index"] intValue]] intValue];
//	int minuteNumber = [[self.minutesArray objectAtIndex: [[self.settingDict objectForKey: @"alerm_minute_index"] intValue]] intValue];
	NSString *musicName = [NSString stringWithFormat: @"%@.caf", soundFile];
    
	NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
	unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | kCFCalendarUnitDay;
	NSDateComponents *dateComps = [calendar components: unitFlags fromDate: [NSDate date]];
    [dateComps setDay: dateComps.day];
    [dateComps setMonth: dateComps.month];
	[dateComps setYear: dateComps.year];
	[dateComps setHour: hourNumber];
	[dateComps setMinute: minuteNumber];
	[dateComps setSecond: 0];
	NSDate *alermDate = [calendar dateFromComponents: dateComps];
	
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = alermDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
	localNotif.repeatInterval = NSDayCalendarUnit;
    localNotif.alertBody = MESSAGE_ALERM;
    localNotif.alertAction = NSLocalizedString(APP_NAME, nil);
    localNotif.soundName = musicName;
    [[UIApplication sharedApplication] scheduleLocalNotification: localNotif];
    [localNotif release];
}

- (void)clearAlerm {
	[[UIApplication sharedApplication] cancelAllLocalNotifications];
}



@end
